<template>
  <div class="box">
    <div class="search-box">
      <div class="search-top-box" :style="moreSearchShow ? 'height:auto;' : ''">
        <div class="search-top-left-box">
          <el-form ref="div" :inline="true" label-width="110px" :model="searchForm" @submit.native.prevent
            class="demo-form-inline">
            <!-- 企业人员 -->
            <template v-if="identity == 1">
              <el-form-item label="关键字：">
                <el-input @change="onSearch(1)" clearable class="form-width" v-model="searchForm.keyword"
                  placeholder="输入关键字"></el-input>
              </el-form-item>
            </template>
            <!-- 施工方 -->
            <template v-if="identity == 2">
              <el-form-item label="关键字：">
                <el-input @change="onSearch(1)" clearable class="form-width" v-model="searchForm.keyword"
                  placeholder="输入关键字"></el-input>
              </el-form-item>
            </template>
            <!-- 客户列表 -->
            <template v-if="identity == 4">
              <el-form-item label="用户名称：">
                <el-input @change="onSearch(1)" clearable class="form-width" v-model="searchForm.keyword"
                  placeholder="输入用户名称"></el-input>
              </el-form-item>
              <el-form-item label="客户类型：">
                <el-select filterable v-model="searchForm.customer_type" placeholder="选择客户类型" clearable class="form-width">
                  <el-option v-for="item in customerTypeList" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="业务区域：">
                <el-select filterable multiple collapse-tags @change="businessAreaChange"
                  v-model="searchForm.business_area_id" placeholder="选择业务区域" clearable class="form-width">
                  <el-option v-for="item in cityList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="会员编号：">
                <el-input @change="onSearch(1)" clearable class="form-width" v-model="searchForm.keyword"
                  placeholder="输入会员编号"></el-input>
              </el-form-item>
              <el-form-item label="会员年龄：">
                <el-input @change="onSearch(1)" clearable class="form-width" v-model="searchForm.keyword"
                  placeholder="输入会员年龄"></el-input>
              </el-form-item>
              <el-form-item label="客户性别：">
                <el-select filterable v-model="searchForm.customer_type" placeholder="选择客户性别" clearable class="form-width">
                  <el-option v-for="item in customerSexList" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="客户身份：">
                <el-select filterable v-model="searchForm.customer_type" placeholder="选择客户身份" clearable class="form-width">
                  <el-option v-for="item in identityList" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="对客关注度：">
                <el-select filterable v-model="searchForm.customer_type" placeholder="选择对客关注度" clearable class="form-width">
                  <el-option v-for="item in attentionList" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="年度开店计划：">
                <el-select filterable v-model="searchForm.customer_type" placeholder="选择年度开店计划" clearable class="form-width">
                  <el-option v-for="item in annualStoreOpeningPlan" :key="item.value" :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="投资能力：">
                <el-select filterable v-model="searchForm.customer_type" placeholder="选择投资能力" clearable class="form-width">
                  <el-option v-for="item in investmentCapabilityList" :key="item.value" :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-form>
        </div>
        <div class="search-top-right-box">
          <p v-if="showOpne" @click="moreSearch">
            {{ moreSearchShow ? "收起" : "展开"
            }}<i :class="moreSearchShow ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
              "></i>
          </p>
          <el-button type="primary" @click="onSearch(1)">查询</el-button>
          <el-button type="primary" @click="addUserModel" v-if="$isPer(permission, ['admin_addAdmin'])">添加用户</el-button>
        </div>
      </div>
    </div>

    <!-- 列表 -->
    <div class="page-list" v-loading="loading">
      <div class="list-top-box">
        <p class="list-top-box-left">
          已选<span class="num">{{ multipleSelection.length }}</span>/{{ tableData.length }}数据
        </p>
        <div class="list-top-box-right">
          <el-button style="opacity: 0;">块</el-button>
          <el-button type="primary" :disabled="multipleSelection.length != 1"
            @click="editEven('', 'detail')">详情</el-button>
          <el-button type="primary" :disabled="multipleSelection.length != 1"
            @click="editEven(multipleSelection[0], 'admin_updateAdmin')"
            v-if="$isPer(permission, ['admin_updAdmin'])">编辑</el-button>
          <el-button type="danger" plain :disabled="multipleSelection.length == 0"
            @click="editEven(multipleSelection[0], 'admin_deleteAdmin')"
            v-if="$isPer(permission, ['admin_delAdmin'])">删除</el-button>
        </div>
      </div>
      <!-- stripe -->
      <div class="table-box">
        <el-table height="100%" :data="tableData" style="width: 100%" :header-cell-style="{
          background: '#FAFBFC',
          color: '#828A9D',
          textAlign: 'center',
        }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="80"></el-table-column>
          <el-table-column prop="" label="头像" width="50px">
            <template slot-scope="scope">
              <img class="avatar-itme" :src="scope.row.image" />
            </template>
          </el-table-column>
          <el-table-column prop="" label="名称" show-overflow-tooltip>
            <template slot-scope="scope">
              <div class="name-item">{{ scope.row.name }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="手机号" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="" label="归属城市" v-if="identity != 4" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.area }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip v-if="identity == 3 || identity == 4" prop="brand_name" label="品牌">
          </el-table-column>
          <el-table-column show-overflow-tooltip v-if="identity == 1 || identity == 2" prop="position" label="职务">
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="role_name" label="角色权限" v-if="identity != 4">
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="updated_at" label="更新时间">
          </el-table-column>
          <el-table-column prop="" label="操作" width="240">
            <template slot-scope="scope">
              <template v-if="$isPer(permission, ['admin_userInheritance'])">
                <el-button v-if="
                  scope.row.position_id == 2 ||
                  scope.row.position_id == 3 ||
                  scope.row.position_id == 5 ||
                  scope.row.position_id == 8 ||
                  scope.row.position_id == 7
                " type="text" @click="editEven(scope.row, 'jcProject')">项目继承</el-button>
              </template>
              <el-button type="text" v-if="
                scope.row.login_fail_num >= 3 &&
                $isPer(permission, ['admin_removeLoginRestrictions'])
              " @click="editEven(scope.row, 'removeLoginRestrictions')">解锁登录</el-button>
              <el-button v-if="projectSearchState && identity == 4" type="text"
                @click="editEven(scope.row, 'project')">项目列表</el-button>
              <el-button type="text" @click="editEven(scope.row, 'admin_updateAdmin')"
                v-if="$isPer(permission, ['admin_updAdmin'])">修改</el-button>
              <el-button type="text" @click="editEven(scope.row, 'admin_deleteAdmin')"
                v-if="$isPer(permission, ['admin_delAdmin'])">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="page-footer">
        <el-pagination background layout="total, sizes, prev, pager, next, jumper" :page-size="num"
          :current-page.sync="page" :total="total" @current-change="pageChange" @size-change="handleSizeChange">
        </el-pagination>
      </div>
    </div>

    <!-- 弹窗 -->
    <el-dialog :title="userFormType == 'add' ? '添加用户' : '修改用户'" :visible.sync="dialogFormVisible" @close="saveUserClose"
      :close-on-click-modal="false" width="460px">
      <el-form :model="userForm" :rules="userRules" class="user-info" ref="userFrom" label-width="110px"
        label-position="left">
        <el-form-item label="用户头像">
          <el-upload action="#" list-type="picture-card" :show-file-list="false" :on-change="change_file"
            accept=".png,.jpeg,.jpg,.webp" :auto-upload="false">
            <img v-if="userForm.imgUrl" :src="userForm.imgUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名称" prop="name">
          <el-input clearable v-model="userForm.name" placeholder="请输入用户名称"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input maxlength="11" clearable v-model="userForm.phone" type="number"
            oninput="if(value.length > 11) value=value.slice(0, 11)" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="userFormType == 'add'">
          <el-input clearable v-model="userForm.password" placeholder="请输入登录密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="所属城市" prop="city">
          <el-cascader v-model="userForm.city" :options="cityList" placeholder="请选择所属城市" clearable
            :props="{ expandTrigger: 'hover', label: 'name', value: 'id' }">
          </el-cascader>
        </el-form-item>
        <el-form-item v-if="userInfo.position_id == 1 && userForm.position_id == 2" label="优惠(对客报价)"
          prop="discount_ratio">
          <el-input clearable v-input-limit="2" v-model="userForm.discount_ratio" placeholder="请输入优惠比例（0%~100%）">
            <span slot="suffix">%</span>
          </el-input>
        </el-form-item>
        <el-form-item v-if="userForm.position_id == 2 && userInfo.position_id == 1" label="优惠(尾款)"
          prop="settlement_discount_ratio">
          <el-input clearable v-input-limit="2" v-model="userForm.settlement_discount_ratio" placeholder="请输入优惠金额">
            <!-- <span slot="suffix">%</span> -->
          </el-input>
        </el-form-item>
        <el-form-item label="职务" prop="position_id" v-if="identity == 1 || identity == 2">
          <el-select filterable @change="positionChange" clearable v-model="userForm.position_id" placeholder="请选择职务">
            <el-option v-for="item in organizationList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品牌" prop="brand_id" v-if="identity == 3 || identity == 4">
          <el-select filterable clearable v-model="userForm.brand_id" placeholder="请选择品牌">
            <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工程监理" v-if="identity == 2 && userForm.position_id == 7" prop="engineering_supervision_id">
          <el-select filterable clearable v-model="userForm.engineering_supervision_id" placeholder="请选择工程监理">
            <el-option v-for="item in engineeringSupervisionList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role_id" v-if="identity != 4">
          <el-select filterable clearable v-model="userForm.role_id" placeholder="请选择角色">
            <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveSubmit('userFrom')" :loading="submitBtn">提交</el-button>
        <el-button @click="saveUserClose">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 项目继承 -->
    <el-dialog title="项目继承" :visible.sync="jcDialogVisible" width="400px">
      <!--  v-model="value" -->
      <div style="font-size: 14px; margin-bottom: 10px">继承者</div>
      <el-input style="margin-bottom: 10px" :value="jsCurrUser.name" disabled></el-input>
      <div style="font-size: 14px; margin-bottom: 10px">被继承者</div>
      <el-select v-model="jcUserVal" style="width: 100%" filterable :placeholder="'请选择' + jcPlaceholder">
        <el-option v-for="(item, index) in jcUserList" :key="index" :label="item.name" :value="item.id">
        </el-option>
      </el-select>
      <span slot="footer">
        <el-button type="primary" @click="jcSubmitFunc">提交</el-button>
        <el-button @click="jcDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import permissionApi from "@/api/permissionApi";
import adminApi from "@/api/adminApi";
import commonApi from "@/api/common";
import brandApi from "@/api/brandApi";
import { getUserInfo } from "@/utils/auth";
import store from "@/store";
import { title } from "@/settings";
import projectApi from "@/api/projectApi";

export default {
  name: "",
  props: ["identity", "engineeringSupervisionList", "permission"],
  data() {
    var password = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("密码不能为空"));
      } else if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/.test(value)) {
        callback(new Error("密码须8-16位,包含大小写字母、数字"));
      } else {
        callback();
      }
    };
    var phoneRule = (rule, value, callback) => {
      if (!/^1\d{10}$/.test(value)) {
        return callback(new Error("请输入正确手机号"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      showOpne: false,
      moreSearchShow: false,
      // 城市数据
      cityList: [],
      roleList: [],

      // 用户列表数据
      page: 1,
      num: 10,
      total: 0,
      tableData: [],

      // 查询数据'
      searchForm: {
        keyword: "",
        city: [],
      },
      // 操作用户
      dialogFormVisible: false,
      userRelationList: [],
      userFormType: "add",
      userForm: {
        admin_id: "",
        name: "",
        imgUrl: "",
        imgFile: null,
        phone: "",
        password: "",
        position_id: "",
        brand_id: "",
        role_id: "",
        city: [],
        discount_ratio: "",
        settlement_discount_ratio: "",
        engineering_supervision_id: "",
      },
      userRules: {
        imgUrl: [
          {
            required: true,
            message: "请上传头像",
            trigger: "change",
          },
        ],
        name: [
          {
            required: true,
            message: "请输入用户名称",
            trigger: "change",
          },
        ],
        phone: [
          {
            required: true,
            validator: phoneRule,
            trigger: "change",
          },
        ],
        password: [
          {
            validator: password,
            required: true,
            trigger: "change",
          },
        ],
        city: [
          {
            required: true,
            message: "请选择所属城市",
            trigger: "change",
          },
        ],
        role_id: [
          {
            required: true,
            message: "请选择角色",
            trigger: "change",
          },
        ],
      },
      submitBtn: false,
      organizationList: [], //组织架构列表
      brandList: [], //品牌列表
      userInfo: {}, //用户信息
      projectSearchState: false,
      jcUserList: [], //继承项目对方用户列表
      jcDialogVisible: false,
      jcUserVal: "",
      jsCurrUser: "",
      jcPlaceholder: "请选择",
      multipleSelection: [], //已选择数据
      customerTypeList: [
        {
          label: "VIP客户",
          value: 1,
        },
        {
          label: "优质客户",
          value: 2,
        },
        {
          label: "普通老客户",
          value: 3,
        },
        {
          label: "优质新客户",
          value: 4,
        },
        {
          label: "普通新客户",
          value: 5,
        },
      ],
      customerSexList: [
        {
          label: "男",
          value: 1,
        },
        {
          label: "女",
          value: 2,
        },
      ],
      identityList: [
        {
          label: "老板",
          value: 1,
        },
        {
          label: "合伙人",
          value: 2,
        },
        {
          label: "项目负责人",
          value: 3,
        },
        {
          label: "签约人",
          value: 4,
        },
      ],
      attentionList: [
        {
          label: "持续重点关注",
          value: 1,
        },
        {
          label: "持续关注",
          value: 2,
        },
        {
          label: "定期关注",
          value: 3,
        },
        {
          label: "不定期关注",
          value: 4,
        },
        {
          label: "一般关注",
          value: 5,
        },
      ],
      annualStoreOpeningPlan: [
        {
          label: "不连续且少量开店",
          value: 1,
        },
        {
          label: "不连续且大量开店",
          value: 2,
        },
        {
          label: "持续且少量开店",
          value: 3,
        },
        {
          label: "持续且大量开店",
          value: 4,
        },
      ],
      investmentCapabilityList: [
        {
          label: "100w以下",
          value: 1,
        },
        {
          label: "100-500w",
          value: 2,
        },
        {
          label: "500-1000w",
          value: 3,
        },
        {
          label: "1000w以上",
          value: 4,
        },
      ],
    };
  },
  watch: {
    // "userForm.position_id": (newVal, oldVal) => {
    //   console.log(newVal, oldVal, "newVal, oldVal")
    //   if (newVal == 7) {
    //     this.userRules.engineering_supervision_id = [{
    //       required: true,
    //       message: "请选择工程监理",
    //       trigger: "change"
    //     }]
    //   } else {
    //     delete this.userRules.engineering_supervision_id;
    //   }
    // }
  },
  mounted() {
    this.$once("hook:beforeDestroy", function () {
      window.onresize = null;
    });
    this.onresize(); //监听搜索容器变化
    window.onresize = () => {
      this.onresize(); //监听搜索容器变化
    };
    this.userInfo = getUserInfo();
    console.log(getUserInfo(), "用户信息");
    this.getAdminList();
    this.getRoleList();
    this.getAreaList();
    switch (this.identity) {
      case 1: //企业人员
        this.userRules.position_id = [
          {
            required: true,
            message: "请选择职务",
            trigger: "change",
          },
        ];
        this.getOrganizationList();
        break;
      case 2: //施工方
        this.userRules.position_id = [
          {
            required: true,
            message: "请选择职务",
            trigger: "change",
          },
        ];
        this.getOrganizationList();
        break;
      case 3: //品牌方
        this.userRules.brand_id = [
          {
            required: true,
            message: "请选择品牌",
            trigger: "change",
          },
        ];
        this.getBrandList();
        break;
      case 4: //普通用户
        this.getBrandList();
        this.customerChenk();
        break;
      default:
    }
  },
  methods: {
    //跳转用户项目列表判断
    customerChenk() {
      // 处理权限
      let menu = store.getters.permission_routes;
      let isSales = false;
      let isConstruction = false;
      let arr = [];
      menu.map((item) => {
        if (item.children) {
          item.children.map((item2) => {
            arr.push(item2.path);
          });
        }
      });
      // 是否存在销售列表
      if (arr.indexOf("/project/salesManagement") != -1) {
        isSales = true;
      }
      // 是否存在施工列表
      if (arr.indexOf("/project/constructionManagement") != -1) {
        isConstruction = true;
      }
      if ((isSales && isConstruction) || (isSales && !isConstruction)) {
        this.projectSearchState = 1;
      } else if (!isSales && isConstruction) {
        this.projectSearchState = 2;
      } else {
        this.projectSearchState = 3;
      }
    },
    onresize() {
      let inter = "";
      clearTimeout(inter);
      inter = setTimeout(() => {
        if (!this.$refs.div) return;
        let height = this.$refs.div.$el.offsetHeight;
        height > 45 ? (this.showOpne = true) : (this.showOpne = false);
        this.moreSearchShow = false;
      }, 1000);
    },
    moreSearch() {
      this.moreSearchShow = !this.moreSearchShow;
    },
    // 搜索
    onSearch(page) {
      this.page = page || 1;
      this.getAdminList();
    },
    getAdminList() {
      let that = this;
      var obj = {
        page: this.page,
        num: this.num,
        keyword: this.searchForm.keyword,
        province_id: this.searchForm.city.length ? this.searchForm.city[0] : "",
        city_id: this.searchForm.city.length ? this.searchForm.city[1] : "",
        county_id: this.searchForm.city.length ? this.searchForm.city[2] : "",
        identity: this.identity,
      };
      that.identity == 4 ? that.getUserList(obj) : that.getAdminApi(obj);
    },
    // 客户
    getUserList(obj) {
      let that = this;
      that.loading = true;
      adminApi
        .getUserList(obj)
        .then((res) => {
          console.log(res, "用户列表");
          that.loading = false;
          if (res.code == 200) {
            that.tableData = res.data.list;
            that.total = res.data.max;
          } else {
            if (res.message == "暂无数据") {
              if (that.page == 1) {
                that.tableData = [];
              }
              return;
            }
            that.$message({
              message: res.message,
              type: "warning",
            });
            that.tableData = [];
            that.total = 0;
          }
        })
        .catch((err) => {
          that.loading = false;
          that.$message({
            message: err.message,
            type: "warning",
          });
        });
    },
    // 管理员
    getAdminApi(obj) {
      let that = this;
      that.loading = true;
      adminApi
        .getAdminList(obj)
        .then((res) => {
          console.log(res, "用户列表");
          that.loading = false;
          if (res.code == 200) {
            that.tableData = res.data.list;
            that.total = res.data.max;
          } else {
            if (res.message == "暂无数据") {
              if (that.page == 1) {
                that.tableData = [];
              }
              return;
            }
            that.$message({
              message: res.message,
              type: "warning",
            });
            that.tableData = [];
            that.total = 0;
          }
        })
        .catch((err) => {
          that.loading = false;
          that.$message({
            message: err.message,
            type: "warning",
          });
        });
    },
    searchEvent() {
      this.page = 1;
      this.getAdminList();
    },
    pageChange(page) {
      this.page = page;
      this.getAdminList();
    },

    // 操作用户弹窗 - 头像数据
    change_file(e) {
      this.userForm.imgUrl = e.url;
      this.userForm.imgFile = e.raw;
    },
    addUserModel() {
      let that = this;
      if (this.identity == 4) {
        this.$router.push({
          path: "/customerPage",
          // query: { id: row.id },
        });
        return;
      }
      this.dialogFormVisible = true;
      this.userFormType = "add";
      this.$nextTick(() => {
        this.$refs.userFrom.clearValidate();
      });
    },
    saveUserClose() {
      this.userForm = {
        admin_id: "",
        name: "",
        imgUrl: "",
        imgFile: null,
        phone: "",
        password: "",
        position_id: "",
        brand_id: "",
        role_id: "",
        city: [],
        discount_ratio: "",
        settlement_discount_ratio: "",
        engineering_supervision_id: "",
      };
      this.$nextTick(() => {
        this.$refs.userFrom.clearValidate();
        this.dialogFormVisible = false;
      });
    },
    // 操作用户弹窗 - 提交
    saveSubmit(formName) {
      //平台用户关联
      let userForm = this.userForm;
      let formCustomer = this.formCustomer;
      console.log(
        this.identity == 4 ? formCustomer : userForm,
        "参数",
        this.userFormType
      );
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 管理员添加修改
          // 优惠比例判断
          if (userForm.discount_ratio) {
            var reg = /^(?:100(?:\.0{1,2})?|[1-9]?\d(?:\.\d{1,2})?)$/;
            if (!reg.test(userForm.discount_ratio)) {
              this.$message.warning("请输入0-100的数值");
              return;
            }
          }
          let formdata = new FormData();
          let data = {
            identity: this.identity,
            engineering_supervision_id: userForm.engineering_supervision_id,
            name: userForm.name,
            phone: userForm.phone,
            password: userForm.password,
            province_id: userForm.city[0],
            city_id: userForm.city[1],
            county_id: userForm.city[2],
            role_id: userForm.role_id,
            position_id: userForm.position_id || 0,
            brand_id: userForm.brand_id || 0,
            admin_id: userForm.admin_id,
            discount_ratio: userForm.discount_ratio || 0,
            settlement_discount_ratio: userForm.settlement_discount_ratio || 0,
          };
          if (userForm.imgFile) {
            formdata.append("image", userForm.imgFile || "");
          }
          formdata.append("data", JSON.stringify(data));
          this.submitBtn = true;
          if (this.userFormType == "add") {
            this.addAdmin(formdata);
          } else {
            this.updateAdmin(formdata);
          }
        } else {
          return false;
        }
      });
    },
    // 添加管理员
    addAdmin(userForm) {
      adminApi
        .addAdmin(userForm)
        .then((res) => {
          console.log(res, "addAdmin");
          if (res.code == 200) {
            this.saveUserClose();
            this.getAdminList();
            this.$message({
              type: "success",
              message: "添加成功!",
            });
          } else {
            this.$message.error(res.message);
          }
          this.submitBtn = false;
        })
        .catch((err) => {
          this.submitBtn = false;
          this.$message.error(err.message);
        });
    },
    // 更新管理员
    updateAdmin(userForm) {
      adminApi
        .updAdmin(userForm)
        .then((res) => {
          console.log(res, "updateAdmin");
          if (res.code == 200) {
            this.saveUserClose();
            this.getAdminList();
            this.$message({
              type: "success",
              message: "修改成功!",
            });
          } else {
            this.$message.error(res.message);
          }
          this.submitBtn = false;
        })
        .catch((err) => {
          this.submitBtn = false;
          this.$message.error(err.message);
        });
    },
    //操作事件
    editEven(row, item) {
      let multipleSelection = this.multipleSelection;
      console.log(multipleSelection)
      switch (item) {
        case "detail":
          this.$router.push({
            path: "/customerDetailNewPage",
            query: {
              id: multipleSelection[0].id
            }
          })
          break;
        case "admin_updateAdmin":
          this.saveUser(row);
          break;
        case "admin_deleteAdmin":
          this.identity == 4 ? this.delCustomer() : this.delAdmin(row);
          break;
        case "removeLoginRestrictions":
          this.removeLoginRestrictions(row);
          break;
        case "project": //跳去项目列表
          let projectSearchState = this.projectSearchState;
          if (projectSearchState == 1) {
            this.$router.push({
              path: "/project/salesManagement",
              query: { id: row.id },
            });
          }
          if (projectSearchState == 2) {
            this.$router.push({
              path: "/project/constructionManagement",
              query: { id: row.id },
            });
          }
          break;
        case "jcProject": //项目继承
          console.log(row, "row");
          this.jsCurrUser = row;
          this.getJcList([row.position_id]);
          switch (row.position_id) {
            case 2:
              this.jcPlaceholder = "客户经理";
              break;
            case 3:
              this.jcPlaceholder = "设计师";
              break;
            case 5:
              this.jcPlaceholder = "造价员";
              break;
            case 7:
              this.jcPlaceholder = "工程经理";
              break;
            case 8:
              this.jcPlaceholder = "工程监理";
              break;
            default:
          }
          this.jcUserVal = "";
          this.jcDialogVisible = true;
          break;
        default:
      }
    },
    // 获取继承对方
    getJcList(position_id_arr) {
      let that = this;
      var obj = {
        page: 1,
        num: 9999,
        position_id_arr,
        identity: this.identity,
      };
      adminApi
        .getAdminList(obj)
        .then((res) => {
          console.log(res, "继承人员");
          if (res.code == 200) {
            res.data.list.forEach((item, index) => {
              if (item.id == this.jsCurrUser.id) {
                res.data.list.splice(index, 1);
              }
            });
            this.jcUserList = res.data.list;
          }
        })
        .catch((err) => {
          this.loading = false;
          this.$message({
            message: err.message,
            type: "warning",
          });
        });
    },
    // 继承项目确认
    jcSubmitFunc() {
      let jcUserList = this.jcUserList;
      let jsCurrUser = this.jsCurrUser;
      let jcUserVal = this.jcUserVal;
      if (!jcUserVal) {
        this.$message.warning("请选择将被继承的" + this.jcPlaceholder);
        return;
      }
      let index = jcUserList.findIndex((item) => {
        return item.id == jcUserVal;
      });
      this.$confirm(
        `“${jsCurrUser.name}”即将继承“${jcUserList[index].name}”所有负责项目, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.userInheritance({
            old_user_id: jjcUserVal,
            new_user_id: jsCurrUser.id,
          });
        })
        .catch(() => { });
    },
    // 继承项目请求
    userInheritance(data) {
      projectApi
        .userInheritance(data)
        .then((res) => {
          console.log(res, "项目继承");
          if (res.code == 200) {
            this.$message.success("操作成功");
            this.jcDialogVisible = false;
          } else {
            this.$message.warning(res.message);
          }
        })
        .catch((err) => {
          this.$message.warning(err.message);
        });
    },
    // 解除登录限制
    removeLoginRestrictions(row) {
      this.$confirm("此操作将解除该用户登录限制, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          adminApi
            .removeLoginRestrictions({
              admin_id: row.id,
            })
            .then((res) => {
              console.log(res, "解除登录限制");
              if (res.code == 200) {
                this.$message.success("操作成功");
                this.getAdminList();
              } else {
                this.$message.warning(res.message);
              }
            })
            .catch((err) => {
              this.$message.warning(err.message);
            });
        })
        .catch(() => { });
    },
    // 编辑用户
    saveUser(row) {
      console.log(row, "saveUser");
      if (this.identity == 4) {
        this.$router.push({
          path: "/customerPage",
          query: { id: row.id },
        });
        return;
      }
      this.userForm.admin_id = row.id;
      this.userForm.name = row.name;
      this.userForm.imgUrl = row.image;
      this.userForm.phone = row.phone;
      this.userForm.city = [row.province_id, row.city_id, row.county_id];
      this.userForm.role_id = row.role_id == 0 ? "" : row.role_id;
      this.userForm.brand_id = row.brand_id == 0 ? "" : row.brand_id;
      this.userForm.position_id = row.position_id == 0 ? "" : row.position_id;
      this.userForm.discount_ratio = row.discount_ratio;
      this.userForm.settlement_discount_ratio = row.settlement_discount_ratio;
      this.userForm.engineering_supervision_id =
        row.engineering_supervision_id == 0
          ? ""
          : row.engineering_supervision_id;
      this.userFormType = "edit";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.userFrom.clearValidate();
      });
    },
    // 删除客户
    delCustomer() {
      let multipleSelection = this.multipleSelection;
      console.log(multipleSelection)
      let id_arr = [];
      multipleSelection.forEach(item => {
        id_arr.push(item.id)
      })
      this.$confirm('是否删除已选中用户?', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        adminApi
          .delUser({
            id_arr,
          })
          .then((res) => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getAdminList();
            } else {
              this.$message.error(res.message);
            }
          });
      });
    },
    // 删除管理员
    delAdmin(row) {
      this.$confirm('是否删除 "' + row.name + '" 用户?', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        adminApi
          .delAdmin({
            admin_id: row.id,
          })
          .then((res) => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getAdminList();
            } else {
              this.$message.error(res.message);
            }
          });
      });
    },
    // 获取角色列表
    getRoleList() {
      permissionApi
        .getRoleList({
          page: 1,
          num: 999,
        })
        .then((res) => {
          console.log(res, "角色列表");
          if (res.code == 200) {
            this.roleList = res.data.list;
          }
        });
    },
    // 省市区
    getAreaList() {
      commonApi.getAreaList().then((res) => {
        console.log(res, "省市区");
        if (res.code == 200) {
          this.cityList = res.data;
        }
      });
    },
    // 组织架构列表
    getOrganizationList() {
      adminApi
        .getOrganizationList({
          type: this.identity == 2 ? 1 : 2,
        })
        .then((res) => {
          console.log(res, "组织架构列表");
          if (res.code == 200) {
            this.organizationList = res.data;
          }
        });
    },
    // 品牌列表
    getBrandList() {
      brandApi
        .getBrandList({
          page: 1,
          num: 999,
        })
        .then((res) => {
          console.log(res, "品牌列表");
          if (res.code == 200) {
            this.brandList = res.data.list;
          }
        });
    },
    // 单文件上传
    uploadFile(data) {
      return new Promise((resolve, reject) => {
        commonApi.uploadFile(data).then((res) => {
          // console.log(res, "单文件上传");
          resolve(res);
        });
      });
    },
    // 职位筛选
    positionChange(e) {
      this.userForm.engineering_supervision_id = "";
      if (e == 7) {
        this.userRules.engineering_supervision_id = [
          {
            required: true,
            message: "请选择工程监理",
            trigger: "change",
          },
        ];
      } else {
        delete this.userRules.engineering_supervision_id;
      }
      this.$nextTick(() => {
        this.$refs.userFrom.clearValidate();
      });
    },
    // 页数改变
    handleSizeChange(e) {
      this.num = e;
      this.page = 1;
      this.getAdminList();
    },
    handleSelectionChange(e) {
      console.log(e);
      this.multipleSelection = e;
    },
    // 业务区域选择
    businessAreaChange(e) {
      let searchForm = this.searchForm;
      searchForm.business_area = [];
      let cityList = this.cityList;
      e.forEach((k) => {
        let index = cityList.findIndex((item) => {
          return item.id == k;
        });
        searchForm.business_area.push(cityList[index].name);
      });
      this.searchForm = searchForm;
    },
  },
};
</script>

<style lang="scss" scoped>
@import './index.scss';
@import '../../styles/listPage.scss';
</style>
